import React, { Component } from "react"
import { Modal, message, Select } from 'antd'
import { openModal, removeContainer } from "components/method/openModal"
import { messages, queryCurrencyPrecision } from "share/common"
import ResizeTable from "components/resize-table/resize-table"
import httpFetch from "share/httpFetch"
import EditCell from "../../pay/template/edit-cell"
import accurateFloat from 'containers/expense-report/template/accurate-float'

const { Option } = Select;

class AmortizationEdit extends Component {

  state = {
    confirmLoading: false,
    loading: false,
    data: [],
    total: {},
    diffIndex: null
  };

  componentDidMount = () => {
    this.setState({ loading: true });
    const { record } = this.props;
    httpFetch.get(`/api/expense/amortization/finance/query`, { expenseApportionmentId: record.expenseApportionmentId })
      .then(res => {
        let total = res.data.reduce((current, item) => {
          current.baseAmount = accurateFloat.add(item.baseAmount, current.baseAmount);
          current.amortizationRate = accurateFloat.add(item.amortizationRate, current.amortizationRate);
          return current
        }, {
          baseAmount: 0,
          amortizationRate: 0
        });
        this.setState({ data: res.data, total });
      })
      .catch(e => {
        message.error(e.response.data.message);
      })
      .finally(() => {
        this.setState({ loading: false });
      })
  };

  columns = [
    { dataIndex: 'expenseTypeName', title: messages('common.expense.type')/*费用类型*/ },
    { dataIndex: 'departmentName', title: messages('common.department')/*部门*/ },
    {
      dataIndex: 'costCenterItems', title: messages('finance-8.key1')/*成本中心*/,
      render: value => JSON.parse(value).map(item => item.costCenterItemName).join(',')
    },
    { dataIndex: 'baseCurrencyCode', title: messages('finance-8.key2')/*本币币种*/ },
    {
      dataIndex: 'baseAmount', title: messages('finance-8.key3')/*摊销金额*/,
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.baseCurrencyCode))
    },
    {
      dataIndex: 'amortizationRate', title: messages('finance-8.key4')/*摊销比例*/,
      render: (value, record) => (
        <EditCell
          step={0.01}
          precision={2}
          render={value => value + '%'}
          value={accurateFloat.multiply(value, 100)}
          onChange={editValue => this.handleValue(editValue, record)}
        />
      )
    },
    { dataIndex: 'periodSetCode', title: messages('finance-8.key5')/*摊销期间*/ },
  ];

  handleValue = (value, record) => {
    const { data, total } = this.state;
    let flag = false;
    let result = value || 0;
    data.map(item => {
      if (item.expenseAmortizationId === record.expenseAmortizationId && item.amortizationRate * 100 !== result) {
        item.amortizationRate = accurateFloat.divide(result, 100);
        item.baseAmount = (total.baseAmount * result / 100 / total.amortizationRate).toFixed(queryCurrencyPrecision(item.baseCurrencyCode));
        flag = true;
      }
      return item
    });
    flag && this.setState({ data });
  };

  handleOk = () => {
    const { data, total } = this.state;
    let result = data.reduce((current, item) => {
      current.amortizationRate = accurateFloat.add(parseFloat(item.amortizationRate), current.amortizationRate);
      current.baseAmount = accurateFloat.add(parseFloat(item.baseAmount), current.baseAmount);
      return current
    }, {
      amortizationRate: 0,
      baseAmount: 0
    });
    if (result.amortizationRate === total.amortizationRate) {
      if (result.baseAmount === total.baseAmount) {
        this.handleSubmit();
      } else {
        Modal.confirm({
          title: messages('finance-8.key6')/*容差处理*/,
          content: (
            <div>
              选择第
              <Select
                placeholder={messages('common.please.select')/*请选择*/}
                onChange={key => this.setState({ diffIndex: key })}
                style={{ width: '100px' }}
              >
                {data.map((item, index) => <Option key={index}>{index}</Option>)}
              </Select>
              条记录做容差
            </div>
          ),
          onOk: () => this.handleDiff(result.baseAmount, total.baseAmount)
        })
      }
    } else {
      message.error(messages('finance-8.key7')/*摊销总比例需等于可摊销总比例*/)
    }
  };

  handleSubmit = () => {
    const { data } = this.state, { onOk } = this.props;
    this.setState({ confirmLoading: true });
    onOk(data.map(item => ({
      expenseAmortizationId: item.expenseAmortizationId,
      baseAmount: item.baseAmount,
      amortizationRate: item.amortizationRate,
      operationType: 1003
    })), this)
  };

  handleDiff = (baseAmount, total) => {
    const { diffIndex, data } = this.state;
    if (!diffIndex) {
      message.error(messages('finance-8.key8')/*请选择一行记录来处理容差*/)
    } else {
      data[diffIndex] = {
        ...data[diffIndex],
        baseAmount: parseFloat(total) - parseFloat(baseAmount) + parseFloat(data[diffIndex].baseAmount)
      };
      this.setState({ data }, this.handleSubmit)
    }
  };

  render() {
    const { visible, onCancel, afterClose, record } = this.props;
    const { confirmLoading, data, loading, total } = this.state;
    return (
      <Modal
        title={messages('finance-8.key9')/*修改摊销*/}
        visible={visible}
        onCancel={onCancel}
        onOk={this.handleOk}
        afterClose={afterClose}
        width={760}
        confirmLoading={confirmLoading}
      >
        <div>
          {messages('finance-8.key10')/*此分摊行下可摊销总金额*/}：
          {record.baseCurrencyCode}
          <span className="num-style">{this.filterMoney(total.baseAmount, queryCurrencyPrecision(record.baseCurrencyCode), true)}</span>
          <span className="ant-divider"/>
          {messages('finance-8.key11')/*可摊销总比例*/}：
          {accurateFloat.multiply(total.amortizationRate, 100) + '%'}
        </div>
        <ResizeTable
          dataSource={data}
          loading={loading}
          columns={this.columns}
          size="middle"
          bordered
        />
      </Modal>
    )
  }

}

AmortizationEdit.open = function(env, props) {
  let container;
  return new Promise(resolve => {
    const targetProps = {
      visible: true,
      onOk: (data, context) => close(data, context),
      onCancel: () => close(null),
      afterClose: () => {
        removeContainer(container);
        container = null;
      },
      ...props
    };
    function close(data, context) {
      let closeModal = () => openModal(AmortizationEdit, {
        ...targetProps,
        visible: false
      }, env, container);
      if (data !== null) resolve({ data, closeModal, context });
      else closeModal();
    }
    container = openModal(AmortizationEdit, targetProps, env);
  });
};

export default AmortizationEdit
